package com.example.test.controller;

import com.example.test.group.UserGroup;
import com.example.test.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import com.example.test.entity.User;
import com.example.test.entity.Role;
import com.example.test.entity.News;
import com.example.test.entity.UserRole;
import com.example.test.util.ResultBean;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired //@Resource也可以
    private UserService userService;

    private static int numInstances = 0;
    private int numInstances1 = 0;

    @PostMapping("/list")
    public ResultBean list() {
        List<User> user = userService.findAll();
        return ResultBean.success(user);
    }

    @PostMapping("/news")
    public ResultBean allNews() {
        List<News> news = userService.findAllNews();
        return ResultBean.success(news);
    }

    @PostMapping("/test")
    public String test() {
//        String str2= new String("Runoob");
//        Integer num = 100000;
//        int num2 = 100000;
//        System.out.println(num==num2);
//        Test.numInstances++;
//        Test test = new Test();
//        test.numInstances1++;
//        System.out.println(Test.numInstances);
//        System.out.println(test.numInstances1);
//        Set set = new HashSet<>();
//        set.add(num2);
//        set.add(num2);
//        System.out.println(set);
//        return str2+num;
        String s = "3.1234567";
        double a = Double.parseDouble(s);
        double b = 5.12;
        Double c = 5.12;
        System.out.println(b==c);
        return "浮点型:" + a;
    }

    @PostMapping("/news2")
    public List<Map<String, Object>> allNews2() {
        List res = new ArrayList();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map1.put("name", "hhhh");
        Map<String, Object> info1 = new HashMap<>();
        info1.put("id", 1);
        info1.put("age", 11);
        map1.put("info", info1);
        res.add(map1);
        map2.put("name", "bbbbb");
        Map<String, Object> info2 = new HashMap<>();
        info2.put("id", 2);
        info2.put("age", 22);
        map2.put("info", info2);
        res.add(map2);
        return res;
    }

    @PostMapping("/news/comments")
    public List<News> newComments() {
        return userService.findNewComments();
    }

    @PostMapping("/news/comments2")
    public List<Map<String, Object>> newComments2(@RequestParam Map<String, Object> post) {
        Integer page = Integer.parseInt(post.get("page").toString());
        Integer pageSize = Integer.parseInt(post.get("page_size").toString());
        System.out.println(page);
        System.out.println(pageSize);
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        System.out.println(page);
        System.out.println(pageSize);
        Integer offset = page - 1;
        return userService.findNewComments2(offset, pageSize);
    }

    @PostMapping("/index")
    public Map<String, Object> index() {
        Map<String, Object> result = new HashMap<>();
        List<User> user = userService.userList();
        for (int i = 0; i < user.size(); i++) {
            System.out.println(user.get(i).getId());
            System.out.println(user.get(i).getUsername());
        }
        result.put("list", user);
        return result;
    }

    @PostMapping("/info")
    public User info(User user) {
        int uid = user.getId();
        return userService.get(uid);
    }

    @PostMapping("/list2")
    public Map<String, Object> list2() {
        Map<String, Object> result = new HashMap<>();
        List<User> user = userService.userList2();
        result.put("list", user);
        return result;
    }

    @PostMapping("/selectPage")
    public List<User> selectPage(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        pageNum = (pageNum - 1) > 0 ? pageNum : 0;
        pageSize = (pageSize - 1) > 0 ? pageSize : 2;
        return userService.selectPage(pageNum, pageSize);
    }

    @RequiresPermissions("user-add")//权限管理
    @PostMapping("/add")
    public ResultBean add(@RequestBody User user) {

        String Salt = new SecureRandomNumberGenerator().nextBytes().toHex();
        //加密
        SimpleHash simpleHash = new SimpleHash("md5",user.getPassword(),Salt,2);
        String newPassword = simpleHash.toString();
        user.setPassword(newPassword);
        user.setSalt(Salt);
        int id = userService.save(user);
        if (id > 0) {
            return ResultBean.success();
        } else {
            return ResultBean.error(500, "保存失败");
        }
    }

    @PostMapping("/save")
    public ResultBean save(@Validated(UserGroup.Add.class) User user){
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        Integer age = user.getAge();
        System.out.println("姓名：" + username + ", 密码: " + password + "邮件: " + email);
        int id = userService.save(user);
        if (id > 0) {
            return ResultBean.success();
        } else {
            return ResultBean.error(500, "保存失败");
        }
    }

    @PostMapping("/save/user/role")
    public String saveUserRole(User user, Role role, UserRole userRole) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        int roleId = role.getRoleId();
        System.out.println("姓名：" + username + ", 密码: " + password + "邮件: " + email);
        if(username == null || username.equals("")){
            throw new Exception("用户名不能为空");
        }
        if(password == null || password.equals("")){
            throw new Exception("密码不能为空");
        }
        if(email == null || email.equals("")){
            throw new Exception("邮箱不能为空");
        }
        System.out.println("姓名：" + username + ", 密码: " + password + "邮件: " + email);
        System.out.println("角色id：" + roleId);
        userService.save(user);
        int uid = user.getId();
        System.out.println("uid：" + uid);
        userRole.setUid(uid);
        userRole.setRoleId(roleId);
        System.out.println(userRole);
        userService.saveUserRole(userRole);
        int id = userRole.getId();
        return "记录id:" + id;
    }

}